import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadDemo14 {
    public static void main(String[] args) throws InterruptedException {
//生产者消费者模型
        BlockingQueue<Integer> queue =new LinkedBlockingQueue<Integer>();
        Thread t1 =new Thread(() ->{
            while(true){

                    try {
                        //阻塞队列取出刚刚添加的元素,赋值,打印
                        int value =queue.take();
                        System.out.println("消费水平: "+ value);

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
            }
        });
        //启动线程
        t1.start();
        Thread t2 =new Thread(() ->{
            Random random =new Random();
            while(true){

                try {
                    Thread.sleep(1000);
                    int num =random.nextInt(100);
                    System.out.println("生产元素:"+num);
                    //阻塞队列添加用户输入的元素
                    queue.put(num);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //t2线程启动
        t2.start();
        //t2线程等待t1线程执行完
        t1.join();
        //t1线程等待t2线程执行完
        t2.join();
    }
}
